package com.song.tools.generator.util;

import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 属性文件工具类
 *
 * @version v1.0
 * @author: fengjinsong
 * @date: 2024年07月14日 11时35分
 */
@Slf4j
public class PropertiesUtil {

    public static final String MYSQL_PROPERTIES_FILE_NAME = "mysql.properties";

    public static final String GENERATOR_CONFIG_PROPERTIES_FILE_NAME = "generatorConfig.properties";

    private static final Map<String, Properties> PROPERTIES_MAP = new HashMap<>(16);

    /**
     * 读取属性文件
     *
     * @param fileName 属性文件名称
     */
    public static void readProperties(String fileName) {
        Properties prop = new Properties();
        try (InputStream input = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName)) {
            if (input == null) {
                log.warn("property file '{}' not found in the classpath", fileName);
                return;
            }

            // load a properties file
            prop.load(input);

            PROPERTIES_MAP.put(fileName, prop);
        } catch (Exception ex) {
            log.error("readProperties error", ex);
        }
    }

    public static String getProperty(String fileName, String key) {
        Properties prop = PROPERTIES_MAP.get(fileName);
        if (prop == null) {
            readProperties(fileName);
            prop = PROPERTIES_MAP.get(fileName);
        }

        if (prop == null) {
            return null;
        }
        return prop.getProperty(key);
    }

    public static String getMysqlProperty(String key) {
        return getProperty(MYSQL_PROPERTIES_FILE_NAME, key);
    }

    public static String getGeneratorConfigProperty(String key) {
        return getProperty(GENERATOR_CONFIG_PROPERTIES_FILE_NAME, key);
    }

    public static class MysqlProperties {
        public static final String URL = getMysqlProperty("mysql.url");
        public static final String USERNAME = getMysqlProperty("mysql.username");
        public static final String PASSWORD = getMysqlProperty("mysql.password");
    }

    public static class GeneratorConfigProperties {
        public static final String AUTHOR = getGeneratorConfigProperty("generator.config.author");

        public static final String PARENT_PACKAGE = getGeneratorConfigProperty("generator.config.parentPackage");

        public static final String DELETE_COLUMN_NAME = getGeneratorConfigProperty("generator.config.deleteColumnName");

        public static final String TABLE_NAME_PREFIX = getGeneratorConfigProperty("generator.config.tableNamePrefix");

        public static final String PROJECT_DIR = getGeneratorConfigProperty("generator.config.projectDir");
    }
}
